import 'dart:math';
import 'package:flutter/material.dart';
import 'package:bts_toolbox/core/get_points_from_json.dart';
import 'package:bts_toolbox/core/bts_billing.dart';
// import 'package:bts_toolbox/core/polyline_interpolator.dart';

class BillingPage extends StatefulWidget {
  const BillingPage({super.key});
  @override
  State<BillingPage> createState() => _BillingPageState();
}

class _BillingPageState extends State<BillingPage>
    with AutomaticKeepAliveClientMixin {
  int _counter = 0;
  String? _calculationResult = '';
  final String finalString = 'You have pushed the button\nthis many times:';
  final TextEditingController _totalInvestmentController =
      TextEditingController();
  final TextEditingController _constructionCostController =
      TextEditingController();

  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context); // 调用父类的build方法
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _billingResultText(), // 计费结果文本
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            spacing: 5, // 增加间隙
            children: [
              SizedBox(width: 35, height: 35, child: _settingsButton()),
              SizedBox(
                width: 123,
                height: 35,
                child: TextField(
                  style: const TextStyle(fontSize: 12),
                  maxLines: 1,
                  controller: _totalInvestmentController,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: '总投资',
                    suffixText: ' 万',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(40),
                      gapPadding: 3.0,
                    ),
                  ),
                ), // 总投资文本框
              ), // 总投资输入文本

              SizedBox(
                width: 103,
                height: 35,
                child: TextField(
                  style: const TextStyle(fontSize: 12),
                  maxLines: 1,
                  controller: _constructionCostController,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: '下浮率',
                    suffixText: ' %',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(40),
                      gapPadding: 3.0,
                    ),
                  ),
                ), // 下浮率文本框
              ),
              SizedBox(width: 68, height: 35, child: _calculatorButton()),
              // 计算按钮
            ],
          ), // 计费输入行
        ],
      ),
    );
  }

  Text _billingResultText() {
    return Text(
      '$finalString\n $_counter\n\n$_calculationResult\n',
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 16),
    );
  }

  ElevatedButton _calculatorButton() {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
        alignment: Alignment.center,
      ),
      child: const Text('Go'),
      onPressed: () {
        // 这里可以添加计费相关的操作
        setState(() {
          _onCalculatorButtonPressed();
        });
      },
      onLongPress: () {
        // 这里可以添加长按相关的操作
        setState(() {
          _onCalculatorButtonLongPress();
        });
      },
    );
  }

  IconButton _settingsButton() {
    return IconButton(
      icon: Icon(Icons.settings, size: 19),
      style: IconButton.styleFrom(
        foregroundColor: Colors.white,
        backgroundColor: Colors.blue.shade500,
      ),
      onPressed: () {
        setState(() {
          _onCalculatorButtonLongPress();
        });
      },
    );
  }

  void _onCalculatorButtonPressed() async {
    try {
      // 将文本转换为double类型
      double billAmount = _totalInvestmentController.text.isNotEmpty
          ? double.parse(_totalInvestmentController.text)
          : 0.0;
      double constructionCost = _constructionCostController.text.isNotEmpty
          ? double.parse(_constructionCostController.text)
          : 0.0;
      List<Map<String, dynamic>> billingType = [
        {'she_ji_fei': '设计费'},
        {'jian_li_fei': '监理费'},
        {'gong_cheng_zhao_biao_dai_li': '工程招标'},
        {'fu_wu_zhao_biao_dai_li': '服务招标'},
        {'gai_suan': '项目概算'},
        {'yu_suan': '工程预算'},
        {'quan_guo_cheng_zao_jia': '全过程造价'},
        {'jian_guan_fei': '建设管理费'},
      ];
      List<String> resultStrings = [];
      for (int i = 0; i < billingType.length; i++) {
        List<Point<double>> feePoints = await GetPoints(
          billingType[i].keys.first,
          'assets/data/rate.json',
        ).jsonToPointList();
        // 按类型计费
        Point<double> resultPoint = Billing(
          feePoints,
          billAmount,
        ).linearInterpolate();
        String finalResultY = (resultPoint.y * (1 - constructionCost / 100))
            .toStringAsFixed(3);
        String finalResultZ =
            (((resultPoint.y * (1 - constructionCost / 100)) / billAmount) *
                    100)
                .toStringAsFixed(3);
        resultStrings.add(
          '${billingType[i].values.first}：$finalResultY 万元｜$finalResultZ%费率',
        );
      }
      _calculationResult = resultStrings.join('\n');
    } catch (e) {
      _calculationResult = '请输入有效数字';
    }
    // 打印计算结果
    setState(() {
      _counter++;
      _calculationResult;
    });
  }

  void _onCalculatorButtonLongPress() {
    _totalInvestmentController.clear();
    _constructionCostController.clear();
    _counter = 0;
    _calculationResult = '';
  }
}
